<?php

namespace app\company\controller;

use app\admin\model\express\Companys;
use app\admin\model\money\Change;
use app\admin\model\product\Category;
use app\admin\model\product\Listo;
use app\admin\model\product\Lists;
use app\admin\model\product\Order;
use app\admin\model\Transport;
use app\common\controller\CompanyApi;
use app\common\controller\Kd100;
use think\Db;
use think\Exception;
use think\Request;

class Productlisto extends CompanyApi
{
    protected static $model = null;
    protected $noNeedLogin = ['logisticsInfo'];
    protected $noNeedRight = '*';

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        self::$model = new Listo();
    }

    /**
     * 获取商品清单表
     */
    public function index()
    {
        $pageSize = $this->request->post('page_size', 15);
        $status = $this->request->post('status');
        $type = $this->request->post('type', 1);
        $user = $this->auth->getUser();
        $department_id = $user->department_id;
        $cateIds = Category::where('department_id', $department_id)->column('id');
        $ids = Lists::where('category_id', 'in', $cateIds)->column('id');
        $where = [
            'product_id' => ['in', $ids]
        ];

        if ($status) {
            $where['status'] = ['in', $status];
        } else {
            $where['status'] = ['>=', 1];
        }

        if (!$type) {
            $type = 1;
        }
        $ids = Lists::where('type', $type)->column('id');
        $where['product_id'] = ['in', $ids];
        $lists = self::$model
//            ->field('listo.id,tag,product_id,product_name,num,price,parameters,listo.pay_time')
            ->where($where)
            ->order('id desc')
            ->paginate($pageSize);

        foreach ($lists as &$val) {
            $pInfo = Lists::where('id', $val['product_id'])->find();
////            $val['goodname'] = $pInfo['goodname'];
            $val['cover_ico'] = make_full_url($pInfo['image']);
            $val['intro'] = $pInfo['intro'];
        }

        $this->success('申请列表！', $lists);
    }

    public function read()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error('参数缺失！');
        }
        $row = self::$model->find($id);
        if (!$row) {
            $this->error('该订单不存在！');
        }

        $row->reply_image = make_full_url($row->reply_image);
        $row->review_image1 = make_full_url($row->review_image1);
        $row->review_image2 = make_full_url($row->review_image2);

        $user = \app\admin\model\User::field('username,nickname')->find();
        $row->user = $user;

        $this->success('登记详情', $row);
    }

    /**
     * 管理员审核
     */
    public function audit()
    {
        $id = input('id');
        $orderInfo = self::$model->where('id', $id)->find();
        if (!$orderInfo) {
            $this->error('该申请单不存在！');
        }

        if ($orderInfo->status != 1) {
            $this->error('该申请单不可审核！');
        }

        $userId = $this->auth->id;
        $lInfo = Lists::where('id', $orderInfo->product_id)->find();
        $ret = $this->checkAuth($userId, $lInfo->category_id);
        if ($ret['code'] == 0) {
            $this->error($ret['msg']);
        }

        $review_image = $this->request->post('review_image1');
        $review_remark = $this->request->post('review_remark1');
        $status = $this->request->post('status');
        if (!$review_image) {
            $this->error('审核人员必须签名！');
        }

        if (!in_array($status, [5, 10])) {
            $this->error('审核错误！');
        }

        if ($status == 10 && $lInfo->stock < $orderInfo->num) {
            $this->error('该物品余量已不足！');
        }

        Db::startTrans();
        try {

            $orderInfo->review_id1 = $userId;
            $orderInfo->review_image1 = $review_image;
            $orderInfo->review_remark1 = $review_remark;
            $orderInfo->send_time = time();
            $orderInfo->status = $status;
            $ret = $orderInfo->save();

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        if (!$ret) {
            $this->error('审核失败');
        }

        $this->success('审核成功！');
    }

    /**
     * 领导复核
     */
    public function review()
    {
        $id = input('id');
        $orderInfo = self::$model->where('id', $id)->find();
        if (!$orderInfo) {
            $this->error('该申请单不存在！');
        }

        if ($orderInfo->status != 10) {
            $this->error('该申请单不可审核！');
        }

        $userId = $this->auth->id;
        $lInfo = Lists::where('id', $orderInfo->product_id)->find();
        $ret = $this->checkLeaderAuth($userId, $lInfo->category_id);
        if ($ret['code'] == 0) {
            $this->error($ret['msg']);
        }

        $review_image = $this->request->post('review_image2');
        $review_remark = $this->request->post('review_remark2');
        $status = $this->request->post('status');
        if (!$review_image) {
            $this->error('审批领导必须签名！');
        }

        if (!in_array($status, [15, 20])) {
            $this->error('审核错误！');
        }

        if ($status == 20 && $lInfo->stock < $orderInfo->num) {
            $this->error('该物品余量已不足！');
        }

        Db::startTrans();
        try {

            $orderInfo->review_id2 = $userId;
            $orderInfo->review_image2 = $review_image;
            $orderInfo->review_remark2 = $review_remark;
            $orderInfo->finish_time = time();
            $orderInfo->status = $status;
            $ret = $orderInfo->save();

            if ($status == 20) {
                $lInfo->stock -= $orderInfo->num;
                $lInfo->save();

                $num = Listo::where('order_id', $orderInfo->order_id)
                    ->where('status', '<', 20)
                    ->count();
                if ($num <= 0) {
                    Order::where('id', $orderInfo->order_id)->update(['finish_time' => time(), 'status' => 20]);
                }

                $orderNum = create_order($id);
                $change_type = 2;
                if ($lInfo->type == 2) {
                    $change_type = 3;
                }
                $department_id = Category::where('id', $lInfo->category_id)->value('department_id');
                $mdata = [
                    'order_num' => $orderNum,
                    'record_type' => 0,
                    'product_id' => $orderInfo->product_id,
                    'change_type' => $change_type,
                    'moneytype' => $lInfo->type,
                    'number' => $orderInfo->num,
                    'hasnumber' => $lInfo->stock,
//                'remark' => $tag,
                    'user_id' => $orderInfo->community_id,
                    'relation_id' => $id,
                    'targetuserid' => $department_id
                ];

                Change::create($mdata);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        if (!$ret) {
            $this->error('审批失败');
        }

        $this->success('审批成功！');
    }

    // 超级管理员下单

    /**
     * 物资结算
     */
    public function preOrder()
    {
        $user = $this->auth->getUser();
        if ($user->is_manager != 1) {
            $this->error('非法操作！');
        }
        $data = input('data');
        $community_id = input('community_id');

        if (!$data || !$community_id) {
            $this->error('参数缺失！');
        }

        $dataArr = [];
        $data1 = explode('|', $data);
        foreach ($data1 as $v1) {
            $arr1 = explode(',', $v1);
            $item = [];
            foreach ($arr1 as $v2) {
                $arr2 = explode(':', $v2);
                if ($arr2[0] == 'product_id') {
                    $item['product_id'] = $arr2[1];
                } elseif ($arr2[0] == 'number') {
                    $item['number'] = $arr2[1];
                }
            }

            $dataArr[] = $item;
        }

        if (count($dataArr) <= 0) {
            $this->error('请至少选择一个物资！');
        }

        $id = $this->auth->id;
        $tag = create_order($id);
        $list = [];
        $number = 0;

        $type = 0;
        foreach ($dataArr as $v) {
            if ($v['product_id'] <= 0) {
                $this->error('参数非法！');
            }
            $productInfo = Lists::where('id', $v['product_id'])->find();
            if (!$productInfo) {
                $this->error('该物资不存在！');
            }
            if ($productInfo->stock < $v['number']) {
                $this->error('物资库存不足！');
            }

            if ($type == 0) {
                $type = $productInfo->type;
            } else {
                if ($type != $productInfo->type) {
                    $this->error('物资类型不同，不可同时下单！');
                }
            }

            $time = time();
            $item = [
                'product_id' => $v['product_id'],
                'product_name' => $productInfo->name,
                'num' => $v['number'],
                'user_id' => $id,
                'community_id' => $community_id,
                'tag' => $tag,
                'createtime' => $time,
                'updatetime' => $time
            ];

            array_push($list, $item);

            $number += $v['number'];
        }

        $res = self::$model->insertAll($list);
        if ($res) {
            $this->success('生成物资清单！', $tag);
        } else {
            $this->error('操作失败！');
        }
    }

    /**
     * 获取物资清单
     */
    public function getOrder()
    {
        $user_id = $this->auth->id;
        $user = $this->auth->getUser();
        if ($user->is_manager != 1) {
            $this->error('非法操作！');
        }
        $tag = input('tag');
        $lists = self::$model->field('id,product_id,product_name,num')->where("tag", $tag)->where('user_id', $user_id)->order('id desc')->select();

        $num = 0;
        foreach ($lists as &$val) {
            $pInfo = Lists::where('id', $val['product_id'])->find();
//            $val['goodname'] = $pInfo['goodname'];
            $val['cover_ico'] = make_full_url($pInfo['image']);
            $val['intro'] = $pInfo['intro'];

            $num += $val['num'];
        }

        $data = [
            'list' => $lists,
            'num' => $num,
        ];

        $this->success('物资清单！', $data);
    }

    /**
     * 再次申请
     */
    public function againOrder()
    {
        if (!request()->isPost()) {
            $this->error('非法操作！');
        }
        $user = $this->auth->getUser();
        if ($user->is_manager != 1) {
            $this->error('非法操作！');
        }

        $id = input('id');
        $list = Listo::where('id', $id)->find();

        if (!$list) {
            $this->error('该订单不存在！');
        }

        if (!in_array($list['status'], [5, 15])) {
            $this->error('该申请单不可更改！');
        }

        $reply_image = $this->request->post('reply_image');
        $message = $this->request->post('message');
        if (!$reply_image) {
            $this->error('申请人必须签名！');
        }

        Db::startTrans();
        try {
            $time = time();
            $list->status = 1;
            $list->pay_time = $time;
            $list->reply_image = $reply_image;
            $list->message = $message;

            $list->review_id1 = 0;
            $list->review_image1 = '';
            $list->review_remark1 = '';
            $list->send_time = 0;

            $list->review_id2 = 0;
            $list->review_image2 = '';
            $list->review_remark2 = '';
            $list->finish_time = 0;
            $res = $list->save();

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('提交成功，等待审核！');
    }

    /**
     * 申请单列表
     */
    public function lists()
    {
        $user = $this->auth->getUser();
        if ($user->is_manager != 1) {
            $this->error('非法操作！');
        }
        $pageSize = input('page_size', 15);
        $community_id = $this->request->post('community_id');
        if (!$community_id) {
            $this->error('参数缺失！');
        }
        $status = $this->request->post('status');
        if (!$status) {
            $status = [-1];
        } else {
            $status = explode(',', $status);
        }

        $user_id = $this->auth->id;
        $map = [
            'user_id' => $user_id,
            'community_id' => $community_id,
        ];
        if (!in_array(-1, $status)) {
            $map['status'] = ['in', $status];
        }

        $lists = Listo::where($map)->paginate($pageSize);
        if ($lists) {
            foreach ($lists as $val) {
                $pInfo = Lists::where('id', $val['product_id'])->find();
                $val['type'] = $pInfo['type'];
                $val['intro'] = $pInfo['intro'];
                $val['image'] = make_full_url($pInfo['image']);
            }
        }

        $this->success('申请单列表', $lists);
    }
}